package com.library.framework.manager;


import com.library.framework.config.CosConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.net.URL;
import java.util.Date;

/**
 * 对象存储上传工具类
 *
 * @auther: wanghongjie
 * @blame: wanghongjie
 * @date: 2020-05-04 10:27
 * @Description:
 */
@Component
public class CosUploadManager {


    public static String uploadFilePubReadPivWrite(byte[] cosFile, CosConfig cosConfig, String concat) {
        COSCredentials cred = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());
        ClientConfig clientConfig = new ClientConfig(new Region("ap-beijing"));
        // 3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        String bucketName = cosConfig.getBucketName();
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(cosFile.length);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, concat, new ByteArrayInputStream(cosFile), objectMetadata);
        cosClient.putObject(putObjectRequest);
        cosClient.shutdown();
        Date expiration = new Date(System.currentTimeMillis() + (long) Integer.parseInt(cosConfig.getExpiration()) * 60 * 10000);
        URL url = cosClient.generatePresignedUrl(bucketName, concat, expiration);
        return "https://".concat(url.getHost()).concat(url.getPath());
    }

    public String getUploadUrl(CosConfig cosConfig, String key) {
        COSCredentials cred = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());
        ClientConfig clientConfig = new ClientConfig(new Region("ap-beijing"));
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosclient = new COSClient(cred, clientConfig);
        Date expirationTime = new Date(System.currentTimeMillis() + 2 * 60 * 1000);
        URL url = cosclient.generatePresignedUrl(cosConfig.getBucketName(), key, expirationTime, HttpMethodName.PUT);
        return url.toString();
    }

}
